﻿using BattleServer.Battle;
using PECommon;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BattleServer
{
    /// <summary>
    /// 服务器基本逻辑单位，多个组件组成
    /// </summary>
    public class SUnit : SLogicBase
    {
        protected int mUid;
        private readonly Dictionary<int, SUnitComp> mCompDic = new Dictionary<int, SUnitComp>();
        protected SWorld mWorld;
        public SWorld World { get { return mWorld; } }
        public int UID { get => mUid; set => mUid = value; }

        public SUnit(int uid)
        {
            this.UID = uid;
        }

        /// <summary>
        /// 挂载组件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public T AddComp<T>() where T : SUnitComp, new()
        {
            T comp = new T();
            comp.Parent = this;
            if(comp is IAwake awakeComp) mAwakeList.Add(awakeComp);
            if(comp is IUpdate updateComp) mUpdateList.Add(updateComp);
            if(comp is IDestory destoryComp) mDestroyList.Add(destoryComp);
            int hashCode = typeof(T).GetHashCode();
            if (!mCompDic.ContainsKey(hashCode))
            {
                mCompDic.Add(hashCode, comp);
            }
            return comp;
           
        }
        /// <summary>
        /// 获取组件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public T GetComp<T> () where T : SUnitComp, new()
        {
            int hashCode = typeof(T).GetHashCode();
            if (mCompDic.ContainsKey(hashCode))
            {
                SUnitComp comp = mCompDic[hashCode];
                if (comp != null && comp is T)
                {
                    return comp as T;
                }

            }
            else
            {
                this.Error($"Get this comp [{typeof(T)}] is not exist!");
            }
            return null;
        }

    }
    /// <summary>
    /// 逻辑单位组件类型
    /// </summary>
    public enum SUnitCompType
    {
        None = 0,
        Attrs, //玩家属性组件，怪物属性组件，效果属性组件
        Move, //移动组件
        Net,    //网络组件
        AOI,    //AOI组件
        Scope,  //作用域组件
        Skill, //技能组件
        AI,  //AI战斗组件

        //业务组件
        Task,  //任务组件
        Team, //组件组件
        
    }

   /// <summary>
   /// 基本角色单位抽象组件
   /// </summary>
    public abstract class SUnitComp
    {
        public int UID { get => Parent.UID; }
        public SUnit Parent;
        public SUnitCompType CompType;
        public float DeltaTime
        {
            get {
                if (Parent.World != null)
                {
                    return Parent.World.Container.DeltaTime;
                }
                return 0f;
            }
        }

        public T AddComp<T>() where T : SUnitComp, new()
        {
            return Parent.AddComp<T>();
        }
    }
}
